import Vue from 'vue'
import Vuex from 'vuex'
import {ajax} from '@/api'
import vuexPersistedstate from 'vuex-persistedstate'   // Vuex 持久化
Vue.use(Vuex)

export default new Vuex.Store({
  plugins:[
    vuexPersistedstate()   
  ],
  state: {
    count:2000,
    userInfo:null,
    city:null , // 当前的城市信息数据
    cityList:[] , // 所有的城市列表 
    cinemaList:[]  , // 当前城市所有的电影院 
    goodList:[]  ,  // 所有的商品数据 
    cartList:[] , // 我的购物车 
  },
  getters: {
    cartNum(state){
      return state.cartList.length;
    },
    hotCity(state){
      return state.cityList.filter(item=>item.isHot==1)
    },
    ntypes(state){
      var arr = [
        {
          text:"全部商品",
          value:"all"
        }
      ]
      var obj = {}
      for(var i=0;i<state.goodList.length;i++){
          var item = state.goodList[i]
          if(!obj[item.type.text]){
              obj[item.type.text] = item.type.text
              arr.push(item.type)
          }
      }
      return arr;
    }
  },
  actions: {
    async getGoodList({commit},payload){
      let res = await ajax.getGoods(payload);
      commit("changegoodList",res)
    },
    async getCinemaList({commit},{cityId,callback}){
      let res= await ajax.getMaizuo({cityId},{
        'X-Host': 'mall.film-ticket.cinema.list'
      })
      callback(res.data.cinemas)
      commit("changeCimenaList",res.data.cinemas)
    },
    async getCityListAsync({commit},payload){
      // 不能使用 this 
      let res = await ajax.getMaizuo({
        k: 829636
      },{
        'X-Host': 'mall.film-ticket.city.list'
      })
      console.log(res);
      commit("getCityList",res.data.cities)
    }
  },
  mutations: {
    changeCount(state,payload){
      state.count += payload; 
    },
    changeUserInfo(state,payload){
      state.userInfo = payload; 
    },
    changeCity(state,payload){
      state.city = payload;
    },
    getCityList(state,payload){
      state.cityList = payload; 
    },
    changeCimenaList(state,payload){
      state.cinemaList = payload;
    },
    changegoodList(state,payload){
      state.goodList = payload;
    },
    getCartList(state,payload){
      console.log(payload)
      state.cartList = payload;
    }
  },
 
  modules: {
  }
})
